package com.codewithmosh.store.services;

import com.codewithmosh.store.dto.OrderVo;
import com.codewithmosh.store.entities.Order;
import com.codewithmosh.store.entities.User;
import com.codewithmosh.store.exceptions.OrderNotFoundException;
import com.codewithmosh.store.mapper.OrderMapper;
import com.codewithmosh.store.repositories.OrderRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class OrderService {
    private final OrderRepository orderRepository;
    private final AuthService authService;
    private final OrderMapper orderMapper;

    public List<OrderVo> getAllOrders() {
        User user = authService.getCurrentUser();

        List<Order> orders = orderRepository.getOrdersByCustomer(user);

        return orders.stream().map(orderMapper::toOrderVo).toList();
    }


    public OrderVo getOrder(Long id) {
        Order order = orderRepository.getOrderWithItems(id).orElseThrow(OrderNotFoundException::new);

        User user = authService.getCurrentUser();
        if (!order.isPlacedBy(user)) {
            throw new AccessDeniedException("You are not authorized to view this order");
        }

        return orderMapper.toOrderVo(order);
    }
}
